const webim = require('../../utils/webim_wx.js')
const getLatestGroupHistoryMsgs = require('./webimUtil.js').getLatestGroupHistoryMsgs
const getGroupHistoryMsgsFromSeq = require('./webimUtil.js').getGroupHistoryMsgsFromSeq
const sendTextMessageToGroup = require('./webimUtil.js').sendTextMessageToGroup
const sendPictureMessageToGroup = require('./webimUtil.js').sendPictureMessageToGroup
const sendVoiceMessageToGroup = require("./webimUtil").sendVoiceMessageToGroup
const sendVideoMessageToGroup = require("./webimUtil").sendVideoMessageToGroup
const formatTime = require('../../utils/util.js').formatTime2
const uploadImage = require('../../utils/API').uploadImage
const uploadAudio = require('../../utils/API').uploadAudio
const uploadVideo = require('../../utils/API').uploadVideo
const getResourceUrl = require('../../utils/API').getResourceUrl
const login = require('../../utils/API').login
const msgType = require('./msgType.js')

const targetGroupId = '@TGS#3Z2GS4QFR'

// 在收到Message对象后 解析后添加到数组中
/*
	解析规则：
		1.仅第一个元素有效，这意味着 图片、表情、语音等消息元素，即使复合在一条Message中，也只能解析第一个一卷书
*/
const formatMessage = msg => {

    let elem = msg.getElems()[0]

    let elemType = elem.getType(),
        elemContent = elem.getContent()

    let content = null
    let type = elemType

    try {
        switch (elemType) {
            // 文本，返回文本内容
            case webim.MSG_ELEMENT_TYPE.TEXT:
                content = elemContent.getText()
                break;
            case webim.MSG_ELEMENT_TYPE.CUSTOM:
                type = elemContent.getExt()
                switch (elemContent.getExt()) {
                    // 图片
                    case msgType.picture:
                        content = getResourceUrl(elemContent.getData())
                        break;
                        // 声音
                    case msgType.voice:
                        content = getResourceUrl(elemContent.getData())
                        break;
                    case msgType.video:
                        // 视频
                        content = getResourceUrl(elemContent.getData())
                        break;
                    default:
                        throw new Error('非法自定义消息')
                        break;
                }
                break;
            case webim.MSG_ELEMENT_TYPE.GROUP_TIP:
                throw new Error('receive group tip')
                break;
            default:
                throw new Error('未知消息元素类型: elemType=' + type);
                break;
        }
    } catch (e) {
        console.log(e)
    }
    return {
        type,
        content,
        seq: msg.seq,
        isSend: msg.isSend,
        fromAccount: msg.fromAccount,
        fromAccountNick: msg.fromAccountNick,
        time: msg.time,
        // 仿微信消息界面时间格式
        // 10位时间戳转为13位时间戳
        formattedTime: formatTime(new Date(msg.time * 1000))
    }
}


const loginInfo = {
    sdkAppID: '1400160538',
    identifier: null,
    identifierNick: null,
    accountType: 36862,
    userSig: null
}
const
    listeners = {
        //监听连接状态回调变化事件,必填
        onConnNotify: function(resp) {
                var info;
                switch (resp.ErrorCode) {
                    case webim.CONNECTION_STATUS.ON:
                        webim.Log.warn('建立连接成功: ' + resp.ErrorInfo);
                        break;
                    case webim.CONNECTION_STATUS.OFF:
                        info = '连接已断开，无法收到新消息，请检查下您的网络是否正常: ' + resp.ErrorInfo;
                        console.log(info);
                        wx.showToast({
                            title: info,
                            // icon: 'none'
                        })
                        webim.Log.warn(info);
                        break;
                    case webim.CONNECTION_STATUS.RECONNECT:
                        info = '连接状态恢复正常: ' + resp.ErrorInfo;
                        console.log(info)
                        wx.showToast({
                            title: info,
                            // icon: 'none'
                        })
                        webim.Log.warn(info);
                        break;
                    default:
                        webim.Log.error('未知连接状态: =' + resp.ErrorInfo);
                        break;
                }
            }

            ,
        //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
        onMsgNotify: function(newMsgList) {
            console.log('新消息')
            console.log(newMsgList);
            var sess, newMsg;

            newMsgList.forEach(msg => {

                if (msg.getSession().id() === targetGroupId) { //为当前聊天对象的消息
                    this.setData({
                        messageListTimeOrdered: this.data.messageListTimeOrdered.concat([formatMessage(msg)])
                    })
                    this.selectComponent('.chat__displaying-area').scrollToBottom()
                }
            })
        }

    }

const app = getApp()




Page({

    data: {
        // 按时间顺序排序的消息列表
        messageListTimeOrdered: [],

    },

    onReady() {

        let accountList = ['test', 'test2']

        wx.showActionSheet({
            itemList: accountList,
            success: res => {
                let username = accountList[res.tapIndex]
                loginInfo.identifier = username
                loginInfo.identifierNick = username


                // 登陆服务器
                login(username, '').then(data => {

                    loginInfo.userSig = data.userSig



                }).then(() => {


                    // 登陆im服务器
                    webim.login(
                        loginInfo, {
                            onConnNotify: listeners.onConnNotify.bind(this),
                            onMsgNotify: listeners.onMsgNotify.bind(this)
                        }, {
                            isLogOn: false
                        },
                        resp => {
                            console.log("login success")


                            // 将identifier写入globalData.userInfo
                            app.globalData.userInfo = app.globalData.userInfo || {}
                            app.globalData.userInfo.identifier = loginInfo.identifier

                            getLatestGroupHistoryMsgs(targetGroupId, 10).then(msgList => {
                                console.log(msgList)
                                this.setData({
                                    messageListTimeOrdered: msgList.map(formatMessage)
                                })
                                console.log(msgList.map(formatMessage))
                                this.selectComponent('.chat__displaying-area').scrollToBottom()
                            })
                        },
                        function(err) {
                            console.log('login failed ', err);
                        }
                    );
                })
            },
            fail(res) {
                wx.navigateBack({
                    delta: 1
                })
            }
        })
    },
    // 操作区域发送文本消息事件
    bindSendTextMessage(e) {
        let detail = e.detail
        sendTextMessageToGroup(targetGroupId, detail.message).then(detail.success, detail.failed)
    },
    // 滚动区域拉取历史记录事件
    bindForwardRefresh(e) {
        let detail = e.detail
        let msgsPromise = null
        if (this.data.messageListTimeOrdered.length === 0) {
            msgsPromise = getLatestGroupHistoryMsgs(targetGroupId)
        } else {
            msgsPromise = getGroupHistoryMsgsFromSeq(targetGroupId, this.data.messageListTimeOrdered[0].seq - 1)
        }
        msgsPromise.then(msgs => msgs.map(formatMessage))
            .then(msgs => {
                this.setData({
                    messageListTimeOrdered: msgs.concat(this.data.messageListTimeOrdered)
                })
                console.log(msgs)
            }).then(() => {
                detail.success()
            }, e => {
                detail.failed(e)
            })

    },
    bindSendPictureMessage(e) {
        let detail = e.detail

        uploadImage(detail.imagePath)
            .then(url => sendPictureMessageToGroup(targetGroupId, url))
            .then(() => detail.success(), e => detail.failed(e))

    },
    bindSendVoiceMessage(e) {
        let detail = e.detail

        uploadAudio(detail.voicePath)
            .then(url => sendVoiceMessageToGroup(targetGroupId, url))
            .then(() => detail.success(), e => detail.failed(e))

	},
	bindSendVideoMessage(e) {
		let detail = e.detail

		uploadVideo(detail.videoPath)
			.then(url => sendVideoMessageToGroup(targetGroupId, url))
			.then(() => detail.success(), e => detail.failed(e))

	},

})